<?php
/**
 * Created by PhpStorm.
 * User: Shroom Ari
 * Date: 11/20/14
 * Time: 11:47 AM
 */
class Product extends MY_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->layout->setLayout('backend/index');
        $session_data = $this->session->userdata('logged_in');
        $usergroup_id = $session_data['usergroup_id'];
        if ($usergroup_id!=1) redirect('../petshop');
    }
    public function listProduct(){
        $page = $this->input->get('p');
        $catId = $this->input->get('c');
        $query = $this->input->get('q');
        if (!isset($catId)) $catId = 1;
        if (!isset($page)) $page = 1;
        if (!is_numeric($page)) $page = 1;
        if (!is_numeric($catId)) $catId = 1;
        if (!isset($query)) $query = null;

        $data['seo']['category']= $this->mproductcategory->get_product_category();
        $data['seo']['title']='Product';
        $data['catId'] = $catId;
        $data['query'] = $query;
        $total_product= $this->mproduct->count_all($catId,$query);
        $perpage = 5;
        if (isset($query)) $config['base_url'] = "/petshop/backend/product/listProduct?c=$catId&q=$query&p="; // xác định trang phân trang
        else $config['base_url'] = "/petshop/backend/product/listProduct?c=$catId&p=";
        $config['total_rows'] = $total_product; // xác định tổng số record
        $config['per_page'] = $perpage; // xác định số record ở mỗi trang
        $config['num_links'] = 10;
        $config['cur_page'] =$page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['_config']= $config;
        $data['_page']=$page;
        $offset = ($page-1) * $perpage;
        $data['product']= $this->mproduct->get_product($perpage,$offset,$catId,$query);
        if (isset($_POST['submit']) and $_POST['submit'] == 'delete'){
            $this->mproduct->delete();
        }

        $this->layout->view('backend/layout/product', $data);


    }
    public function delete(){
        $this->mproduct->delete($this->input->post('id'));
    }
    public function newProduct(){
        echo $this->input->post('name');
        $data['seo']['category']= $this->mproductcategory->get_product_category();
        $data['seo']['title']='Add product';
        $data['seo']['keywords']='';
        $data['seo']['description']='';
        if (isset($_POST['submit']) and $_POST['submit'] == 'add'){
            $this->form_validation->set_rules('name', 'Product name', 'required|min_length[3]|xss_clean|callback__name');
            $this->form_validation->set_rules('description', 'Description', 'required|xss_clean');
            $this->form_validation->set_rules('price','Price', 'required|min_length[2]');
            $this->form_validation->set_rules('quantity_remaining','Quantity Remaining', 'required|numeric');
            $this->form_validation->set_rules('category','Product category', 'trim|required');
            //$this->form_validation->set_rules('file','Url Image ', 'trim|required');
            if($this->form_validation->run())
            {
                $data = array(
                    'product_id' =>'',
                    'product_name' => $this->input->post('name'),
                    'description' => $this->input->post('description'),
                    'unit_price' => $this->input->post('price'),
                    'url_image' => $this->save_image(),
                    'quantity_remaining' => $this->input->post('quantity_remaining'),
                    'product_category_id' => $this->input->post('category')
                );
                if($this->mproduct->create($data))
                {
                    redirect('backend/product/listProduct');
                }
            }
        }
        $this->layout->view('backend/layout/new_product', $data);
    }

    function save_image(){
        $name = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10).".jpg";

        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ((($_FILES["file"]["type"] == "image/gif")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/jpg")
                || ($_FILES["file"]["type"] == "image/jpeg")
                || ($_FILES["file"]["type"] == "image/x-png")
                || ($_FILES["file"]["type"] == "image/png"))
            && in_array($extension, $allowedExts)) {
            $file_name = $_SERVER["DOCUMENT_ROOT"]."/petshop/public/images/".$name;
            if(file_exists($file_name)) {
                chmod($file_name,0755); //Change the file permissions if allowed
                unlink($file_name); //remove the file
            }
            if ($_FILES["file"]["error"] > 0) {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
                echo 1;
            }
        }
        return $name;
    }

    public function name($name){
        $count=$this->db->where(array('product_name'=>$name))->from('product')->count_all_results();
        if($count!=0){
            $this->form_validation->set_message('_name','%s is not available');
            return FALSE;
        }
        return TRUE;
    }
    public function edit($id){
        $data['seo']['title']='Edit product';
        $data['seo']['keywords']='';
        $data['seo']['description']='';
        $data['category']= $this->mproductcategory->get_product_category();
        $data['productbyid']= $this->mproduct->get_productbyid($id);
        if (isset($_POST['submit']) and $_POST['submit'] == 'edit'){
            $this->form_validation->set_rules('name', 'Product name', 'required|min_length[3]|xss_clean|callback__name');
            $this->form_validation->set_rules('description', 'Description', 'required|xss_clean');
            $this->form_validation->set_rules('price','Price', 'required|min_length[2]');
            $this->form_validation->set_rules('quantity_remaining','Quantity Remaining', 'required|numeric');
            $this->form_validation->set_rules('category','Product category', 'trim|required');
            //$this->form_validation->set_rules('urlImage','Url Image ', 'trim|required');
            if($this->form_validation->run())
            {
                if ($_FILES["file"]["error"] == 0)
                $dt = array(
                    'product_name' => $this->input->post('name'),
                    'description' => $this->input->post('description'),
                    'unit_price' => $this->input->post('price'),
                    'url_image' => $this->save_image(),
                    'quantity_remaining' => $this->input->post('quantity_remaining'),
                    'product_category_id' => $this->input->post('category')
                );
                else
                    $dt = array(
                        'product_name' => $this->input->post('name'),
                        'description' => $this->input->post('description'),
                        'unit_price' => $this->input->post('price'),
                        'quantity_remaining' => $this->input->post('quantity_remaining'),
                        'product_category_id' => $this->input->post('category')
                    );
                if($this->mproduct->updateProduct($id,$dt))
                {
                    redirect('backend/product/listProduct');
                }
            }
        }
        $this->layout->view('backend/layout/edit_product',$data);
    }

    public function listProductType($page=1){
        $data['seo']['title']='Product Type';
        $total_type= $this->mproducttype->countAll();
        $perpage = 5;
        $config['base_url'] = "/petshop/backend/product/listProductType/"; // xác định trang phân trang
        $config['total_rows'] = $total_type; // xác định tổng số record
        $config['per_page'] = $perpage; // xác định số record ở mỗi trang
        $config['num_links'] = 10;
        $config['cur_page'] =$page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['_config']= $config;
        $data['_page']=$page;
        $offset = ($page-1) * $perpage;
        $data['productType']= $this->mproducttype->getProductType($perpage,$offset);
        if (isset($_POST['submit']) and $_POST['submit'] == 'delete'){
            $this->mproducttype->delete();
        }
        $this->layout->view('backend/layout/product_type', $data);

    }
    public function newProductType(){
        $data['seo']['title']='Add product type';
        if (isset($_POST['submit']) and $_POST['submit'] == 'add'){
            $this->form_validation->set_rules('name', 'Product name', 'required|min_length[3]|xss_clean|callback__name');
            if($this->form_validation->run())
            {
                $data = array(
                    'product_type_id' =>'',
                    'product_type_name' => $this->input->post('name'),

                );
                if($this->mproducttype->create($data))
                {
                    redirect('backend/product/listProductType');
                }
            }
        }
        $this->layout->view('backend/layout/new_product_type', $data);
    }
    public function deleteType(){
        echo $this->mproducttype->delete($this->input->post('id'));
    }
    public function editType($id){
        $data['seo']['title']='Edit product type';
        $data['productTypeById']= $this->mproducttype->getProductTypeById($id);
        if (isset($_POST['submit']) and $_POST['submit'] == 'edit'){
            $this->form_validation->set_rules('name', 'Product Type name', 'required|min_length[3]|xss_clean|callback__name');
            if($this->form_validation->run())
            {
                $dt = array(
                    'product_type_name' => $this->input->post('name'),

                );
                if($this->mproducttype->updateType($id,$dt))
                {

                    redirect('backend/product/listProductType');
                }
            }
        }
        $this->layout->view('backend/layout/edit_product_type', $data);
    }
    public function listProductCategory($page=1){
        $data['seo']['title']='Product Category';
        $data['check_delete'] = true;
        $total_category= $this->mproductcategory->countAll();
        $perpage = 5;
        $config['base_url'] = "/petshop/backend/product/listProductCategory/"; // xác định trang phân trang
        $config['total_rows'] = $total_category; // xác định tổng số record
        $config['per_page'] = $perpage; // xác định số record ở mỗi trang
        $config['num_links'] = 10;
        $config['cur_page'] =$page;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['_config']= $config;
        $data['_page']=$page;
        $offset = ($page-1) * $perpage;
        $data['productCategory']= $this->mproductcategory->getProductCategory($perpage,$offset);
        $this->layout->view('backend/layout/product_category', $data);

    }
    public function newProductCategory(){
        $data['seo']['title']='Add product type';
        if (isset($_POST['submit']) and $_POST['submit'] == 'add'){
            $this->form_validation->set_rules('name', 'Product name', 'required|min_length[3]|xss_clean|callback__name');
            if($this->form_validation->run())
            {
                $data = array(
                    'product_type_id' =>'',
                    'product_type_name' => $this->input->post('name'),

                );
                if($this->mproducttype->create($data))
                {
                    redirect('backend/product/listProductCategory');
                }
            }
        }
        $this->layout->view('backend/layout/new_product_category', $data);
    }
    public function deleteCategory(){
        echo $this->mproductcategory->delete($this->input->post('id'));
    }
    public function editCategory($id){
        $data['seo']['title']='Edit product type';
        $data['productCategoryById']= $this->mproductcategory->getProductCategoryById($id);
        $data['type']= $this->mproducttype->get_product_type();
        if (isset($_POST['submit']) and $_POST['submit'] == 'edit'){
            $this->form_validation->set_rules('name', 'Product Category name', 'required|min_length[3]|xss_clean|callback__name');
            $this->form_validation->set_rules('type','Product Type', 'trim|required');
            if($this->form_validation->run())
            {
                $dt = array(
                    'product_category_name' => $this->input->post('name'),
                    'product_type_id' => $this->input->post('type')

                );
                if($this->mproductcategory->updateCategory($id,$dt))
                {

                    redirect('backend/product/listProductCategory');
                }
            }
        }
        $this->layout->view('backend/layout/edit_product_category', $data);
    }

}